package edu.zut.cs.network.dao.service.runnable;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

import edu.zut.cs.network.base.BaseMainCase;
import edu.zut.cs.network.entity.Book;
/**
 * Description: 读取文件进程实现
 * <p>
 * 逐行读取文件中的数据，按照指定数量组成一组，放入阻塞队列 读取结束，放入结束标识
 * </p>
 * Create: 2018/11/31 17:53
 *
 * @author Yang RuiLong(1094093288@qq.com)
 */
public class InnerReader extends BaseMainCase implements Runnable {




	/** 阻塞队列 */
	private BlockingQueue<List<Book>> blockingQueue;

	/** 输入文件名称 */
	private String inputFileName;

	/** 队列最大长度 */
	private int maxQueueSize;

	/** 一组数据大小 */
	private static final int GROUP_LIMIT = 100;

	/** 结束标识 */
	private static final List<Book> END = new ArrayList<>();
	public InnerReader() {
	}

	public InnerReader(BlockingQueue<List<Book>> blockingQueue, String inputFileName, int maxQueueSize) {
		this.blockingQueue = blockingQueue;
		this.inputFileName = inputFileName;
		this.maxQueueSize = maxQueueSize;
	}
	/**
	 * 阻塞队列中加入数据: 队列满则等待
	 *
	 * @param end2 一组数据
	 * @throws Exception time.sleep
	 */
	private void addDataGroup(List<Book> end2) throws Exception {
		while (blockingQueue.size() >= maxQueueSize) {
			TimeUnit.SECONDS.sleep(3);
		}
		blockingQueue.add(end2);
	}
	@Override
	public void run() {
		File inputFile = new File(inputFileName);
		if (!inputFile.exists()) {
			logger.error("cat not find such file: {}", inputFileName);
			return;
		}
		try {
			BufferedReader bufferedReader = new BufferedReader(new FileReader(inputFile));
			String line;
			String[] onerow;
			List<Book> dataGroup = new ArrayList<>(GROUP_LIMIT);
			while ((line = bufferedReader.readLine()) != null) {
				if (dataGroup.size() >= GROUP_LIMIT) {
					addDataGroup(dataGroup);//将列表加入到队列中
					// 数据重置
					dataGroup = new ArrayList<>(GROUP_LIMIT); 
				}
				Book book = new Book();
				onerow = line.split(","); // 默认分割符为逗号，可以不使用逗号
				List<String> onerowlist = Arrays.asList(onerow);
				book.setBookName(onerowlist.get(0));
				book.setPosition(onerowlist.get(1));
				book.setNumber(onerowlist.get(2));
				book.setId(Long.valueOf(onerowlist.get(3)));
				dataGroup.add(book);
			}
			// 最后一批数据
			addDataGroup(dataGroup);

			// 结束标识
			addDataGroup(END);//END为一个空list
			bufferedReader.close();
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
	}



}
